import requests
from datetime import datetime, timedelta
import time


def get_tiangou_quote():
    time.sleep(1)
    url = "https://v.api.aa1.cn/api/tiangou/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        quote = response.text.replace("<p>", "").replace("</p>", "")
        return quote
    else:
        return None


def save_quote_to_file(quote, date, filename):
    with open(filename, "a", encoding="utf-8") as file:
        file.write(f"## {date}\n{quote}\n")


# 主程序
if __name__ == "__main__":
    current_date = datetime(2023, 11, 4)
    last_saved_date = None
    duplicate_dates = set()
    quote_set = set()
    duplicate_data = set()
    # 读取文档中的日期，并添加到重复日期列表
    with open("quotes1.txt", "r", encoding="utf-8") as file:
        lines = file.readlines()
        for line in lines:
            line = line.strip()
            if line.startswith("##"):
                continue
                # date = line[3:].strip()
                # duplicate_dates.add(date)
            else:
                quote_set.add(line)
    with open("quotes1.txt", "w", encoding="utf-8") as file:
        file.write("")
    while current_date <= datetime(2024, 12, 31):
        if last_saved_date:
            current_date = last_saved_date + timedelta(days=1)

        print(f"当前日期：{current_date.strftime('%Y-%m-%d')}")

        if current_date.strftime('%Y-%m-%d') not in duplicate_dates:
            quote = quote_set.pop() if quote_set else None
            if not quote:
                quote = get_tiangou_quote()
            while not quote or quote in duplicate_data:
                print(f"请求失败或获取到重复的句子！日期"
                      f"：{current_date.strftime('%Y-%m-%d')}，重新请求中...")

                quote = get_tiangou_quote()

            save_quote_to_file(quote, current_date.strftime('%Y-%m-%d'),
                               "quotes1.txt")
            duplicate_dates.add(current_date.strftime('%Y-%m-%d'))  # 更新重复日期列表
            duplicate_data.add(quote)  # 更新重复数据列表
            print(f"保存成功！日期：{current_date.strftime('%Y-%m-%d')}")

        last_saved_date = current_date
        current_date += timedelta(days=1)  # 更新日期


    if len(duplicate_dates) == 0:
        print("没有重复的句子。")